﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.CardAcct.Interfaces;
using PARK.CardAcct.Entitys.Dto.employee;
using PARK.System.Interfaces.Permission;
using PARK.Common.Util;
using PARK.System.Entitys.Permission;
using System.Text;
using PARK.CardAcct.Entitys;
using PARK.CardAcct.BaseEmployeeLog;
using Microsoft.AspNetCore.Http;
using PARK.Common.Configuration;
using PARK.Common.Model.NPOI;
using PARK.DataEncryption;
using PARK.System.Interfaces.Common;
using PARK.CardAcct.Entitys.Dto;
using PARK.System.Interfaces.System;
using PARK.CardAcct.Entitys.Dto.DeskTop;
using PARK.System.Entitys.Model.Permission.User;

namespace PARK.CardAcct.Employee
{
    /// <summary>
    /// 获取管理首页数据
    /// </summary>
    [ApiDescriptionSettings(Tag = "desktop", Name = "rep", Order = 200)]
    [Route("api/desktop/[controller]")]
    public class DeskTopService : IEmployeeService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EmployeeEntity> _baseEmployeeRepository;
        private readonly SqlSugarScope _db;

        /// <summary>
        /// 初始化一个<see cref="DeskTopService"/>类型的新实例
        /// </summary>
        public DeskTopService(
            ISqlSugarRepository<EmployeeEntity> baseEmployeeRepository)
        {
            _baseEmployeeRepository = baseEmployeeRepository;
            _db = _baseEmployeeRepository.Context;
        }

        /// <summary>
        /// 获取首页消费统计
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetRechargAndConsItems")]    
        public async Task<dynamic> GetRechargAndConsItems()
        {
            var user = new UserInfo();
            var _companyId = "00";
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;
                var _userManager = App.GetService<IUserManager>(services);
                user = await _userManager.GetUserInfo();
            });
            if (user != null && user.UserAdminFlag != 2 && !string.IsNullOrEmpty(user.companyId))
            {
                _companyId = user.companyId;
            }
            StringBuilder dbSql = new StringBuilder("exec P_Get_DeskTop_TopData '" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + _companyId + "'");
            var Paras = new List<SugarParameter>();
            var tb = await _db.Ado.GetDataTableAsync(dbSql.ToString(), Paras);
            if (tb != null && tb.Rows.Count > 0)
            {
                return new RechargAndConsItemsOutput()
                {
                    RechargeQty = int.Parse(tb.Rows[0]["RechargeQty"].ToString()),
                    RechargeAmt = decimal.Parse(tb.Rows[0]["RechargeAmt"].ToString()),
                    TxnTotalQty= int.Parse(tb.Rows[0]["TxnTotalQty"].ToString()),
                    TxnTotalAmt = decimal.Parse(tb.Rows[0]["TxnTotalAmt"].ToString()),
                    WelfareConsAmt = decimal.Parse(tb.Rows[0]["WelfareConsAmt"].ToString()),
                    AccConsAmt = decimal.Parse(tb.Rows[0]["AccConsAmt"].ToString())
                };
            }
            else
            {
                return new RechargAndConsItemsOutput()
                {
                    RechargeAmt = 0,
                    TxnTotalAmt = 0,
                    WelfareConsAmt = 0,
                    AccConsAmt = 0,
                    EquerrQty = 0
                };
            }
        }
        /// <summary>
        /// 获取首页最新10条消费记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTop10ConsList")]
        public async Task<dynamic> GetTop10ConsList()
        {
            var user = new UserInfo();
            var _companyId = "00";
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;
                var _userManager = App.GetService<IUserManager>(services);
                user = await _userManager.GetUserInfo();
            });
            if (user != null && user.UserAdminFlag != 2 && !string.IsNullOrEmpty(user.companyId))
            {
                _companyId = user.companyId;
            }
            StringBuilder dbSql = new StringBuilder("select top 10 ConsumKind,TxnTotalAmt,TxnDate,JobNo,ReallName from V_consum_bill where TxnResult=1 and TxnTotalAmt>0 ");
            dbSql.AppendFormat(" and CompanyId='{0}'", _companyId);
            dbSql.Append(" order by dbDate desc");
            var data = await _db.SqlQueryable<ConsItemOutput>(dbSql.ToString()).Select(t => new ConsItemOutput
            {
                ConsumKind = t.ConsumKind,
                TxnTotalAmt = t.TxnTotalAmt,
                TxnDate = Convert.ToDateTime(t.TxnDate).ToString("yyyy-MM-dd HH:mm"),
                JobNo = t.JobNo,
                ReallName = t.ReallName
            }).MergeTable().ToListAsync();
            return data;
        }

        /// <summary>
        /// 获取首页最新10条门禁记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTop10AccessList")]
        public async Task<dynamic> GetTop10AccessList()
        {
            var user = new UserInfo();
            var _companyId = "00";            
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;
                var _userManager = App.GetService<IUserManager>(services);
                user = await _userManager.GetUserInfo();
            });
            if (user != null && user.UserAdminFlag != 2 && !string.IsNullOrEmpty(user.companyId))
            {
                _companyId = user.companyId;
            }
            StringBuilder dbSql = new StringBuilder("select top 10 CardNo,JobNo,ReallName,Isnull(DepartName,'') as DepartName,Passtime,doorAreaName,ctlposition,doorName from V_Access_record where JobNo Is not null ");
            dbSql.AppendFormat(" and CompanyId='{0}'", _companyId);
            dbSql.Append(" order by [Passtime] desc");
            var data = await _db.SqlQueryable<AccessItemOutput>(dbSql.ToString()).Select(t => new AccessItemOutput
            {
                doorAreaName = t.doorAreaName,
                DepartName = t.DepartName,
                ctlposition = t.ctlposition,
                Passtime = Convert.ToDateTime(t.Passtime).ToString("yyyy-MM-dd HH:mm"),
                CardNo = t.CardNo,
                JobNo = t.JobNo,
                ReallName = t.ReallName,
                doorName = t.doorName
            }).MergeTable().ToListAsync();
            return data;
        }

        /// <summary>
        /// 获取首页门禁图表数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTopAccessChart")]
        public async Task<dynamic> GetTopAccessChart()
        {
            var user = new UserInfo();
            var _companyId = "00";            
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;
                var _userManager = App.GetService<IUserManager>(services);
                user = await _userManager.GetUserInfo();
            });
            if (user != null && user.UserAdminFlag != 2 && !string.IsNullOrEmpty(user.companyId))
            {
                _companyId = user.companyId;
            }
            List<AccessChartOutput> output = new List<AccessChartOutput>();
            StringBuilder dbSql = new StringBuilder("exec P_Get_DeskTop_AccessChart '" + _companyId + "'");
            var Paras = new List<SugarParameter>();
            var tb = await _db.Ado.GetDataTableAsync(dbSql.ToString(), Paras);
            if (tb != null && tb.Rows.Count > 0)
            {
                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    output.Add(new AccessChartOutput()
                    {
                        rq = tb.Rows[i]["rq"].ToString(),
                        qty = int.Parse(tb.Rows[i]["qty"].ToString())
                    });
                }
            }
            return output;
        }
    }
}
